"""爬虫配置设置"""

import os
from typing import Dict, Any


class Settings:
    """爬虫配置类"""
    
    # 基础配置
    BASE_URL = "https://www.1688.com"
    SEARCH_URL = "https://s.1688.com/selloffer/offer_search.htm"
    
    # 搜索参数
    DEFAULT_KEYWORDS = ""
    MAX_PAGES = 5
    ITEMS_PER_PAGE = 60
    
    # 延时配置
    MIN_DELAY = 1.0
    MAX_DELAY = 3.0
    PAGE_LOAD_TIMEOUT = 30
    ELEMENT_WAIT_TIMEOUT = 10
    
    # 反爬配置
    USE_SELENIUM = True
    HEADLESS_MODE = True
    MAX_RETRY_TIMES = 3
    RETRY_DELAY = 5.0
    
    # 筛选配置
    FILTER_GUANGZHOU = True
    SORT_BY_SALES = True
    MIN_SALES_COUNT = 0
    
    # 输出配置
    OUTPUT_FORMAT = "json"  # json, csv, both
    OUTPUT_DIR = "output"
    SAVE_IMAGES = False
    
    # 日志配置
    LOG_LEVEL = "INFO"
    LOG_FILE = "crawler.log"
    
    # 浏览器配置
    BROWSER_CONFIG = {
        "window_size": "1920,1080",
        "disable_images": True,
        "disable_css": False,
        "disable_javascript": False,
    }
    
    # 请求头配置
    DEFAULT_HEADERS = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'Cache-Control': 'max-age=0',
    }
    
    # CSS选择器配置
    SELECTORS = {
        "product_list": ".offer-item, .sm-offer-item, [class*='offer-item']",
        "product_title": ".title a, .offer-title a, [class*='title'] a",
        "product_price": ".price, .offer-price, [class*='price']",
        "product_sales": ".sales, .offer-sales, [class*='sales']",
        "product_location": ".location, .offer-location, [class*='location']",
        "product_supplier": ".supplier, .offer-supplier, [class*='supplier']",
        "product_image": "img",
        "next_page": ".next, .fui-next, [class*='next']",
        "sort_sales": "[data-sort='sale'], .sort-sales, [class*='sort'][class*='sales']"
    }
    
    # 搜索URL参数模板
    SEARCH_PARAMS = {
        "keywords": "{keyword}",
        "beginPage": "{page}",
        "sortType": "sale_desc",  # 按销量降序
        "province": "广东",  # 可选：限制省份
        "city": "广州",     # 可选：限制城市
    }
    
    # 多平台支持配置
    PLATFORMS = {
        '1688': {
            'name': '1688',
            'search_url': 'https://s.1688.com/selloffer/offer_search.htm?keywords={keyword}&beginPage={page}',
            'requires_login': True,
            'selectors': {
                'product_list': ['.offer-item', '.sm-offer-item', '.card-item'],
                'product_title': ['.offer-title', '.title', 'h3', 'h4'],
                'product_price': ['.price', '.offer-price', '[class*="price"]'],
                'product_sales': ['.sales', '.deal-cnt', '[class*="sales"]'],
                'product_link': ['a[href]'],
                'product_image': ['img[src]', 'img[data-src]'],
            }
        },
        'taobao': {
            'name': '淘宝',
            'search_url': 'https://s.taobao.com/search?q={keyword}&s={start}',
            'requires_login': False,
            'selectors': {
                'product_list': ['.item', '.Card--doubleCardWrapper--L2XFE73', '[data-category="auctions"]'],
                'product_title': ['.title', '.Title--title--jCOPvpf', 'a[title]'],
                'product_price': ['.price', '.Price--priceInt--ZlsSi_M', '[class*="price"]'],
                'product_sales': ['.deal-cnt', '.SalesCount--soldCount--1nZQjSv', '[class*="sales"]'],
                'product_link': ['a[href]'],
                'product_image': ['img[src]', 'img[data-src]'],
            }
        },
        'jd': {
            'name': '京东',
            'search_url': 'https://search.jd.com/Search?keyword={keyword}&page={page}',
            'requires_login': False,
            'selectors': {
                'product_list': ['.gl-item', '.p-item', '[data-sku]'],
                'product_title': ['.p-name', '.p-name a', 'em'],
                'product_price': ['.p-price', '.price', '[class*="price"]'],
                'product_sales': ['.p-commit', '.p-commit a', '[class*="commit"]'],
                'product_link': ['.p-name a', 'a[href]'],
                'product_image': ['.p-img img', 'img[src]', 'img[data-lazy-img]'],
            }
        }
    }
    
    # 默认平台
    DEFAULT_PLATFORM = 'taobao'
    
    # 备用搜索URL格式（不需要登录）
    SEARCH_URL_TEMPLATE_ALT = "https://s.1688.com/selloffer/offer_search.htm?keywords={keywords}&n=y&sortType={sort_type}&beginPage={page}"
    
    @classmethod
    def get_search_url(cls, keyword: str, page: int = 1) -> str:
        """构建搜索URL"""
        params = []
        for key, value in cls.SEARCH_PARAMS.items():
            if key == "keywords":
                params.append(f"{key}={value.format(keyword=keyword)}")
            elif key == "beginPage":
                params.append(f"{key}={value.format(page=page)}")
            else:
                params.append(f"{key}={value}")
        
        return f"{cls.SEARCH_URL}?{'&'.join(params)}"
    
    @classmethod
    def create_output_dir(cls) -> str:
        """创建输出目录"""
        if not os.path.exists(cls.OUTPUT_DIR):
            os.makedirs(cls.OUTPUT_DIR)
        return cls.OUTPUT_DIR
    
    @classmethod
    def update_from_env(cls) -> None:
        """从环境变量更新配置"""
        cls.MAX_PAGES = int(os.getenv("MAX_PAGES", cls.MAX_PAGES))
        cls.MIN_DELAY = float(os.getenv("MIN_DELAY", cls.MIN_DELAY))
        cls.MAX_DELAY = float(os.getenv("MAX_DELAY", cls.MAX_DELAY))
        cls.HEADLESS_MODE = os.getenv("HEADLESS_MODE", "true").lower() == "true"
        cls.OUTPUT_FORMAT = os.getenv("OUTPUT_FORMAT", cls.OUTPUT_FORMAT)
        cls.LOG_LEVEL = os.getenv("LOG_LEVEL", cls.LOG_LEVEL)


# 初始化时从环境变量更新配置
Settings.update_from_env()